import React, { useRef, useState, useEffect, useCallback } from 'react';
import './index.css';

export default function HaiNengDa() {
    const [playUrl, setPlayUrl] = useState('https://59.198.246.4:28843/live/xxx.fly');
    const [isPlaying, setIsPlaying] = useState(false);
    const jessibucaRef = useRef(null);
    const containerRef = useRef(null);
    const showOperateBtns = true;
    const forceNoOffscreen = false;

    const create = useCallback(() => {
        jessibucaRef.current = new window.Jessibuca({
            container: containerRef.current,
            videoBuffer: 0.2,
            isResize: false,
            text: "",
            loadingText: "加载中",
            debug: true,
            showBandwidth: showOperateBtns,
            operateBtns: {
                fullscreen: showOperateBtns,
                screenshot: showOperateBtns,
                play: showOperateBtns,
                audio: showOperateBtns,
            },
            forceNoOffscreen: forceNoOffscreen,
            isNotMute: false,
        });
    }, [showOperateBtns, forceNoOffscreen]);

    const play = useCallback(() => {
        if (jessibucaRef.current && playUrl) {
            jessibucaRef.current.play(playUrl);
            setIsPlaying(true);
        }
    }, [playUrl]);

    const pause = useCallback(() => {
        if (jessibucaRef.current) {
            jessibucaRef.current.pause();
            setIsPlaying(false);
        }
    }, []);

    const destroy = useCallback(() => {
        if (jessibucaRef.current) {
            jessibucaRef.current.destroy();
            setIsPlaying(false);
        }
    }, []);

    useEffect(() => {
        create();
        return () => {
            destroy();
        };
    }, [create, destroy]);

    return (
        <div className="root">
            <div className="container-shell">
                <div ref={containerRef}></div>
                <div className="input">
                    <div>输入URL：</div>
                    <input
                        autoComplete="on"
                        id="playUrl"
                        value={playUrl}
                        onChange={(e) => setPlayUrl(e.target.value)}
                    />
                    {
                        isPlaying ?
                            <button id="pause" onClick={pause}>停止</button> :
                            <button id="play" onClick={play}>播放</button>
                    }
                </div>
                {
                    isPlaying &&
                    <div className="input">
                        <button id="destroy" onClick={destroy}>销毁</button>
                    </div>
                }
            </div>
        </div>
    );
}